package com.device.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.device.dataobject.ro.TemplateData;
import com.device.dataobject.ro.WxMsgVo;
import com.device.service.WxService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class wxNotifyController {

    final
    WxService wxService;
    @Autowired
    public wxNotifyController(WxService wxService) {
        this.wxService = wxService;
    }

    /**
     * {
     *   "touser": "OPENID",
     *   "template_id": "TEMPLATE_ID",
     *   "page": "index",
     *   "miniprogram_state":"developer",
     *   "lang":"zh_CN",
     *   "data": {
     *       "number01": {
     *           "value": "339208499"
     *       },
     *       "date01": {
     *           "value": "2015年01月05日"
     *       },
     *       "site01": {
     *           "value": "TIT创意园"
     *       } ,
     *       "site02": {
     *           "value": "广州市新港中路397号"
     *       }
     *   }
     * }
     */
    @GetMapping("/wxTest")
    public JSONObject wxTest(String openId, String templateId) {
        WxMsgVo wxMsgVo = new WxMsgVo();
        wxMsgVo.setTouser(openId);
        wxMsgVo.setTemplate_id(templateId);
        wxMsgVo.setPage("pages/index");

        // 模版xiaox
        Map<String, TemplateData> m = new HashMap<>(3);
        m.put("thing4", new TemplateData("Hello"));
        m.put("thing2", new TemplateData("World"));
        m.put("time1", new TemplateData("2020-05-17 19:20:13"));

        wxMsgVo.setData(m);

        return wxService.pushMessage(wxMsgVo);
    }




    @GetMapping(value = "/wxnotify", produces = "text/plain;charset=utf-8")
    public String verify(String signature,long timestamp,String nonce,String echostr){
        String token = "shijinhang";
        ArrayList<String> list = new ArrayList<>();
        list.add(token);
        list.add(Long.toString(timestamp));
        list.add(nonce);

        Collections.sort(list);
        String str1 = String.join("",list);
        String str2 = DigestUtils.sha1Hex(str1);
        log.debug(signature, str2);
        if (signature.equals(str2)){
            return echostr;
        }else {
            return null;
        }
    }

    @PostMapping(value = "/wxnotify", produces = "text/plain;charset=utf-8")
    public String wxnotify(@RequestBody JSONObject jsonObject){
        log.debug("WeChat notify json: " + jsonObject.toJSONString());
        String msgType = jsonObject.getString("MsgType");
        String event = jsonObject.getString("Event");
        String fromUserName = jsonObject.getString("FromUserName");

        // 用户在小程序端同意接收订阅消息
        if ("event".equals(msgType) && "subscribe_msg_popup_event".equals(event)) {
            // JSON里的List元素可能是数组，也可能是对象，需要判断下类型再解析
            JSONArray array;
            if (jsonObject.get("List") instanceof JSONArray) {
                array = jsonObject.getJSONArray("List");
            } else {
                array = new JSONArray();
                array.add(jsonObject.get("List"));
            }

            for (Object item : array) {
                // 至此，就知道哪个openid订阅了哪个template，是否同意接收，根据你的逻辑决定是否存数据库
                JSONObject obj = (JSONObject) JSON.toJSON(item);
                String templateId = obj.getString("TemplateId");
                String subscribeStatusString = obj.getString("SubscribeStatusString");
                log.debug(String.format("User openid: %s subscribe templateid: %s, status: %s", fromUserName, templateId, subscribeStatusString));
            }
        }

        return "success";
    }
}
